//
//  SERegisterViewController.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/12.
//

import UIKit

class SERegisterViewController: SEBaseViewController {

    @IBOutlet weak var phoneTextView: SEAuthTextFildView! {
        didSet {
            phoneTextView.viewType = .account
        }
    }
    @IBOutlet weak var codeTextView: SEAuthTextFildView! {
        didSet {
            codeTextView.viewType = .code
            codeTextView.delegate = self
        }
    }
    @IBOutlet weak var nextBtn: SERegistrationConfirmBtnView! {
        didSet {
            nextBtn.title = "下一步"
            nextBtn.btnBgColor = UIColor.init(hex: "03C691")
            nextBtn.delegate = self
        }
    }

    @IBAction func agreeBtnAction(_ sender: UIButton) {
        sender.isSelected.toggle()
        viewModel.isAgree = sender.isSelected
    }

    @IBAction func showInfoBtnAction(_ sender: UIButton) {
        showAgreementView()
    }

    var viewModel = SEAuthViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        addEndEditingTap()
        // Do any additional setup after loading the view.
    }

    override func setupUI() {
        super.setupUI()
        viewModel.msgCodeHandler = { status in
            switch status {
            case .success:
                SEHUD.show(message: "验证码发送成功")
                self.codeTextView.fireTimer()
            case .auth(let msg), .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

    private func showAgreementView() {
        view.endEditing(true)
        let agreementView = UINib.loadViewFrom(AgreementAlertView.self)
                        agreementView.show(type: .patientRegister)
    }
}

extension SERegisterViewController: SERegistrationConfirmBtnViewDelegate {
    func registrationConfirmBtnViewAction(view: SERegistrationConfirmBtnView) {
        self.view.endEditing(true)
        viewModel.account = phoneTextView.textField.text!
        viewModel.code = codeTextView.textField.text!
        if let msg = viewModel.checkNext {
            SEHUD.showError(message: msg)
            return
        }
        let vc = SERegisterPasswordViewController(with: viewModel)
        navigationController?.pushViewController(vc, animated: true)
    }
}

extension SERegisterViewController: SEAuthTextFildViewDelegate {
    func authTextFildViewCodeBtnAction() {
        view.endEditing(true)
        msgCode()
    }

    private func msgCode() {
        viewModel.account = phoneTextView.textField.text!
        viewModel.requestMsgCode()
    }
}
